package io.github.consoles.distribution;

import java.util.ArrayList;
import java.util.List;
import java.util.zip.CRC32;

/**
 * Created by yiihua-013 on 16/10/25.
 * <p>
 * 分布式取模算法
 */
public class Moder implements Hash, Distribution {

    private List<String> nodes = new ArrayList<>();

    public int getServerSize() {
        return nodes.size();
    }

    @Override
    public String lookup(String key) {
        int serversLen = nodes.size();
        int pos        = (int) (hash(key) % serversLen);
        return nodes.get(pos);
    }

    @Override
    public long hash(String str) {
        CRC32 crc32 = new CRC32();
        crc32.update(str.getBytes());
        long ret = crc32.getValue();
        return ret > 0 ? ret : -ret;
    }

    public void addNode(String node) {
        if (!nodes.contains(node)) nodes.add(node);
    }

    public void deleteNode(String node) {
        nodes.remove(node);
    }
}
